import React, { useEffect, useState } from "react";
import Button from "react-bootstrap/Button";
import Col from "react-bootstrap/Col";
import Form from "react-bootstrap/Form";
import Row from "react-bootstrap/Row";
import InputGroup from "react-bootstrap/InputGroup";
import Card from "react-bootstrap/Card";
import { useRef } from "react";
import WxAuthForm from "./WxAuthForm";
import ideaCanvasService from "../services/ideaCanvasService";
import wxAuthClient from "../utils/wxAuthClient";

const IdeaCanvasForm = () => {
  const formRef = useRef();
  const [generatingCanvas, setGeneratingCanvas] = useState(false);
  const [savingCanvas, setSavingCanvas] = useState(false);
  const [isShowAuthForm, setIsShowAuthForm] = useState(false);

  // add onSubmit function
  const handuleSubmit = (event, v1, v2, v3) => {
    setSavingCanvas(true);
    event.preventDefault();
    const submitData = getFormData();
    console.log("Form submitted", submitData);
    ideaCanvasService
      .createIdeaCanvas(submitData.idea, submitData.canvas_content)
      .then((res) => {
        console.log("Idea canvas saved", res);
      })
      .finally(() => {
        setSavingCanvas(false);
      });
  };

  useEffect(() => {}, []);

  const generateCanvas = async () => {
    setGeneratingCanvas(true);
    const { idea } = getFormData();
    try {
      console.log("generate canvas", idea);
      let canvasData = await ideaCanvasService.getIdeaCanvas(idea);
      canvasData = JSON.parse(canvasData.data);
      console.log("canvasData", canvasData);
      for (var key in canvasData.idea_canvas) {
        var newKey = key;
        if (key == "customer_relationshi") {
          newKey = "customer_relationships";
        } else if (key == "customer_segmentatio") {
          newKey = "customer_segmentation";
        }
        if (formRef.current[newKey]) {
          formRef.current[newKey].value = canvasData.idea_canvas[key];
        } else {
          console.log("missing key", key);
        }
      }
    } catch (error) {
      console.error("Error generating canvas", error);
    }
    setGeneratingCanvas(false);
  };

  const getFormData = () => {
    const formData = new FormData(formRef.current);
    const data = Object.fromEntries(formData.entries());
    const user_idea = data.user_idea;
    delete data.user_idea;
    const submitData = { idea: user_idea, canvas_content: data };
    return submitData;
  };

  return (
    <>
      <Card>
        <Card.Body>
          <Form ref={formRef} onSubmit={handuleSubmit}>
            <InputGroup className="mb-4">
              <Form.Control
                required
                name="user_idea"
                placeholder="你的想法是什么？"
              />
              <Button
                variant="primary"
                disabled={generatingCanvas}
                onClick={generateCanvas}
              >
                {generatingCanvas ? "生成中.." : "智能生成"}
              </Button>
            </InputGroup>

            <Row className="mb-4">
              <Form.Group
                as={Col}
                md={{ span: 2, order: 1 }}
                controlId="formGridEmail"
              >
                <Form.Label>1. 客户细分</Form.Label>
                <Form.Control
                  as="textarea"
                  name="customer_segmentation"
                  rows={12}
                  placeholder="客户细分"
                />
              </Form.Group>

              <Form.Group
                as={Col}
                md={{ span: 2, order: 2 }}
                controlId="formGridEmail"
              >
                <Form.Label>4. 客户关系</Form.Label>
                <Form.Control
                  as="textarea"
                  name="customer_relationships"
                  rows={5}
                  placeholder="客户关系"
                />
                <Form.Label>3. 渠道通路</Form.Label>
                <Form.Control
                  as="textarea"
                  name="channels"
                  rows={5}
                  placeholder="渠道通路"
                />
              </Form.Group>
              <Form.Group
                as={Col}
                md={{ span: 4, order: 3 }}
                controlId="formGridEmail"
              >
                <Form.Label>2. 价值主张</Form.Label>
                <Form.Control
                  as="textarea"
                  name="value_propositions"
                  rows={12}
                  placeholder="价值主张"
                />
              </Form.Group>

              <Form.Group
                as={Col}
                md={{ span: 2, order: 4 }}
                controlId="formGridEmail"
              >
                <Form.Label>7. 关键业务</Form.Label>
                <Form.Control
                  as="textarea"
                  name="key_activities"
                  rows={5}
                  placeholder="关键业务"
                />
                <Form.Label>6. 核心资源</Form.Label>
                <Form.Control
                  as="textarea"
                  name="key_resources"
                  rows={5}
                  placeholder="核心资源"
                />
              </Form.Group>
              <Form.Group
                as={Col}
                md={{ span: 2, order: 5 }}
                controlId="formGridEmail"
              >
                <Form.Label>8. 重要合作</Form.Label>
                <Form.Control
                  name="key_partnerships"
                  as="textarea"
                  rows={12}
                  placeholder="重要合作"
                />
              </Form.Group>
            </Row>

            <Row className="mb-4">
              <Form.Group as={Col} md={6} controlId="formGridEmail">
                <Form.Label>5. 收入来源</Form.Label>
                <Form.Control
                  as="textarea"
                  name="income_streams"
                  rows={12}
                  placeholder="收入来源"
                />
              </Form.Group>
              <Form.Group as={Col} md={6} controlId="formGridEmail">
                <Form.Label>9. 成本结构</Form.Label>
                <Form.Control
                  as="textarea"
                  name="cost_structure"
                  rows={12}
                  placeholder="成本结构"
                />
              </Form.Group>
            </Row>
            <Row>
              <Button variant="primary" type="submit" disabled={savingCanvas}>
                {savingCanvas ? "保存中.." : "保存画布"}
              </Button>
            </Row>
          </Form>
        </Card.Body>
      </Card>
      <WxAuthForm
        isShow={isShowAuthForm}
        onHide={() => setIsShowAuthForm(false)}
      />
    </>
  );
};

export default IdeaCanvasForm;
